package com.lch.webdemo.aop;

import com.lch.webdemo.enums.DataSourceEnum;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 动态切换数据源
 *
 * @author liuchenhui
 * @since
 */
@Order(1)
@Aspect
@Component
public class SwitchDateSourceAop {

    private static final Logger logger = LoggerFactory.getLogger(SwitchDateSourceAop.class);

    @Around("execution(* com.lch.webdemo.dao.mysql..*(..)))")
    public Object proceed(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            logger.debug("调用的sql查询方法名为" + method.getName());
            DataSource dataSource = method.getAnnotation(DataSource.class);
            if (dataSource != null && DataSourceEnum.SLAVE.equals(dataSource.value())) {
                MultipleDataSource.setSlave();
            }
            //如果是默认的select方法，直接切从库
            if (method.getName().startsWith("select")) {
                MultipleDataSource.setSlave();
            }
            MultipleDataSource.setMaster();
            return joinPoint.proceed();
        } catch (Exception e) {
            throw e;
        } finally {
            MultipleDataSource.setMaster();
        }
    }
}
